﻿using System;
using System.Data.SqlClient;

namespace AutoProbe
{
    public class SQLTools
    {
        private readonly string _cs;

        public SQLTools(string CS)
        {
            _cs = CS;
        }

        /// <summary>
        ///   Retourne la version du serveur SQL.
        /// </summary>
        /// <returns></returns>
        public string GetSQLServerVersion()
        {
            return GetScalarValue("SELECT @@VERSION");
        }


        public string GetSQLServerName()
        {
            return GetScalarValue("SELECT @@SERVERNAME");
        }

        /// <summary>
        ///   Medianamik 2.0, retourne les dernières patches intallées
        /// </summary>
        /// <returns></returns>
        public string GetMedianamikLatestPatch()
        {
            return
                GetScalarValue(
                    "SELECT top 1 MajorReleaseNumber + '.' + MinorReleaseNumber + '.' + PointReleaseNumber as ScriptVersion " +
                    "from medianamik_SchemaChange " +
                    "Order by MajorReleaseNumber DESC, MinorReleaseNumber DESC, PointReleaseNumber DESC");
        }


        private string GetScalarValue(string sql)
        {
            var scalarValue = "";

            if (!String.IsNullOrEmpty(_cs))
            {
                var conn = new SqlConnection(_cs);

                try
                {
                    var cmd = new SqlCommand(sql, conn);
                    conn.Open();
                    scalarValue = cmd.ExecuteScalar().ToString();
                }
                catch (Exception exc)
                {
                }
                finally
                {
                    conn.Close();
                }
            }
            return scalarValue;
        }
    }
}